package com.creditease.cn.monitor.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.creditease.cn.monitor.dto.CommandKeyDTO;
import com.creditease.cn.monitor.service.CommandKeyService;
import com.creditease.cn.monitor.service.HashService;
import com.creditease.cn.monitor.service.ListService;
import com.creditease.cn.monitor.service.SetService;
import com.creditease.cn.monitor.service.StringService;
import com.creditease.cn.monitor.service.ZSetService;
import com.creditease.cn.monitor.service.impl.StringServiceImplt;

@Controller
@RequestMapping("/command/key")
public class CommandKeyController extends BaseController{
	private Logger logger = LoggerFactory.getLogger(CommandKeyController.class);
	@Autowired
	private CommandKeyService commandKeyService;
	@Autowired
	private StringService stringService;
	@Autowired
	private ListService listService;
	@Autowired
	private ZSetService zSetService;
	@Autowired
	private HashService hashService;
	@Autowired
	private SetService setService;
	
	
	@RequestMapping("/toIndex")
	public String toIndex(){
		return "/command/key/index.html";
	}
	
	@RequestMapping("/keys")
	public String keys(String pattern,Model model){
		Set<CommandKeyDTO> commandKeyDTOs = commandKeyService.keys(pattern);
		model.addAttribute("commandKeyDTOs", commandKeyDTOs);
		model.addAttribute("pattern", pattern);
		model.addAttribute("totalCount", commandKeyDTOs.size());
		return "/command/key/index.html";
	}
	
	@RequestMapping("/getValue")
	public void getValue(String key,String type,HttpServletResponse response){
		Map<String,Object> result = new HashMap<String,Object>();
		Object value = null;
		long totalCount = 0;
		if(type.equals("string")){
			value = stringService.getValue(key);
			totalCount = 1;
		}else if(type.equals("list")){
			value = listService.getValue(key, 0, -1);
			List<String> valueList = (List<String>) value;
			totalCount = valueList.size();
		}else if(type.equals("zset")){
			value = zSetService.getValue(key);
			Set<String> valueList = (Set<String>) value;
			totalCount = valueList.size();
		}else if(type.equals("hash")){
			value = hashService.getValue(key);
		}else if(type.equals("set")){
			value = setService.getValue(key);
			Set<String> valueList = (Set<String>) value;
			totalCount = valueList.size();
		}
		result.put("key", key);
		result.put("type", type);
		result.put("value", value);
		result.put("totalCount", totalCount);
		ajaxSendJSON(result, response);
	}
}
